package com.flashcards;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.flashcards.auth.OAuth;
import com.flashcards.auth.OAuthConstant;
import com.flashcards.auth.UserInfo;
import com.flashcards.repository.UserInfoRepository;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;
import weibo4andriod.http.RequestToken;

public class Configuration extends Activity {
    private OAuth oAuth;

    public Configuration() {
        oAuth = new OAuth();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.configuration);
        Weibo weibo = OAuthConstant.getInstance().getWeibo();
        RequestToken requestToken = null;
        try {
            requestToken = weibo.getOAuthRequestToken("flashcards://.Configuration");
            Uri uri = Uri.parse(requestToken.getAuthenticationURL() + "&from=xweibo");
            OAuthConstant.getInstance().setRequestToken(requestToken);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
        } catch (WeiboException e) {
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();
        AccessToken accessToken = null;
        try {
            Uri uri = intent.getData();
            String oauth_verifier = uri.getQueryParameter("oauth_verifier");
            accessToken = requestToken.getAccessToken(oauth_verifier);
            OAuthConstant.getInstance().setAccessToken(accessToken);
            UserInfoRepository flashcards = UserInfoRepository.INSTANCE(this);
            OAuthConstant instance = OAuthConstant.getInstance();
            flashcards.save(new UserInfo("",
                                instance.getToken(),
                                OAuthConstant.getInstance().getTokenSecret()));
            startActivity(new Intent(this, FlashCards.class));
        } catch (WeiboException e) {
        }
    }

}

